package com.google.samples.apps.room.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.google.samples.apps.library_common.utils.LogUtils

/**
 * Created by Administrator on 2021/7/9 0009.
 * Describe:
 */
@Database(entities = [User::class], exportSchema = false, version = 1)
abstract class UserDatabase : RoomDatabase() {

    abstract fun userDao(): UserDao

    companion object {
        private val DATABASE_NAME: String = "user_db"
        private var instance: UserDatabase? = null
        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                LogUtils.d("MIGRATION_1_2")
            }

        }

        @Synchronized
        fun getInstance(context: Context): UserDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    DATABASE_NAME
                )
                    .addMigrations(MIGRATION_1_2)
                    .allowMainThreadQueries() // 允许主线程调用
                    .build()
            }
            return instance!!
        }

    }

}